//
//  DBLocalWork.m
//  KidReading
//
//  Created by telen on 15/7/22.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "DBLocalWork.h"
#import "ConstDefine.h"
#import "NSString+pinYin.h"

@interface DBHelper ()<UIAlertViewDelegate>
@end

@implementation DBHelper (DBLocalWork)

static UIAlertView* alter_TokenOutTime = nil;
- (void)showTokenOutMsg:(NSString *)msg
{
    if (alter_TokenOutTime == nil) {
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        [uinfo logout];
        [[CacheData shareSingle] saveUserLoginInfo:uinfo];
        [[RootViewController shareLastInstance] checkTo_Home];
        //
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", "") otherButtonTitles:NSLocalizedString(@"login", ""), nil];
        alter_TokenOutTime = alert;
        [DataProcessing do_Main:^{
            [alert show];
        } delay:0.5];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 0) {
        [[RootViewController shareLastInstance] load_UserInfo_Server_Login:nil];
    }
    else if(buttonIndex == 1) {
       [[RootViewController shareLastInstance] yzt_Login:NO];
    }
    alter_TokenOutTime = nil;
}


- (void)selectReadingCountList:(void (^)(NSDictionary* dict))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"readingCount" : list});
    } fromTableClass:NSStringFromClass([TABLE_READING_COUNT class]) where:@""];
}

- (LongLong)selectReadingCount_forBookId:(NSInteger)bookId db:(JRFMDatabase*)db
{
    NSArray* list = [self getList_fromTableClass:NSStringFromClass([TABLE_READING_COUNT class]) where:[NSString stringWithFormat:@" where bookId = '%@'",@(bookId)] db:db];
    for (TABLE_READING_COUNT* tb_rc in list) {
        //NSLog(@"rCount %lld",tb_rc.rCount);
        return tb_rc.rCount;
    }
    return 0;
}


- (void)selectBookList_Books:(NSString *)bookIds complete:(void (^)(NSDictionary *))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"book" : list});
    } fromTableClass:NSStringFromClass([TABLE_BOOKS class]) where:[NSString stringWithFormat:@" where bookId in (%@)",bookIds]];
}
- (void)selectBookList_Books:(NSString *)bookIds limit:(long)lt complete:(void (^)(NSDictionary *))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"book" : list});
    } fromTableClass:NSStringFromClass([TABLE_BOOKS class]) where:[NSString stringWithFormat:@" where bookId in (%@) limit %ld",bookIds,lt]];
}

- (NSDictionary *)selectBookList_Books:(NSString *)bookIds db:(JRFMDatabase *)db
{
    NSArray* list = [self getList_fromTableClass:NSStringFromClass([TABLE_BOOKS class]) where:[NSString stringWithFormat:@" where bookId in (%@)",bookIds] db:db];
    return @{@"book" : list};
}

- (void)selectBookWithReadCountList_Books:(NSString *)bookIds complete:(void (^)(NSDictionary *))complete
{
    BOOL isChinese = [DataProcessing shareSingle].isChineseForLocalSystem;
    NSString* rCount = @"rCount";
    NSString* bookId = @"bookId";
    NSString* where_book = [NSString stringWithFormat:@"select * from '%@' where bookId in (%@)",[TABLE_BOOKS tableName],bookIds];
    NSString* where_rCount = [NSString stringWithFormat:@"select * from '%@' where bookId in (%@)",[TABLE_READING_COUNT tableName],bookIds];
    [self readerDB:^(JRFMDatabase *db) {
        NSArray* bkarr = [self getDictList_where:where_book db:db];
        NSArray* rcarr = [self getDictList_where:where_rCount db:db];
        [DataProcessing do_Async_quick:^{
            NSMutableArray* marr = [NSMutableArray new];
            NSMutableDictionary* mdict = [NSMutableDictionary new];
            for (NSDictionary* dic in rcarr) {
                NSNumber* bkid = dic[bookId];
                [mdict setObject:dic[rCount] forKey:bkid.description];
            }
            for (NSDictionary* dict in bkarr) {
                TABLE_BOOKS* obj = [TABLE_BOOKS JRMJ_objectWithKeyValues:dict];
                if ([obj isKindOfClass:[TABLE_base class]]) {
                    NSDictionary* replaceKeys = [[obj class] replacedKeyFromPropertyName];
                    for (NSString* key in replaceKeys) {
                        id value = dict[key];
                        if (value && [obj hasProperty:key]) {
                            [obj setValue:value forKey:key];
                        }
                    }
                }
                NSNumber* number = mdict[@(obj.bookId).description];
                nullToNil(number);
                obj.rCount = [number integerValue];
                obj.name_pinyin = isChinese ? obj.name_zh.pinyin : obj.name_en;
                if (obj) {
                    [marr addObject:obj];
                }
            }
            [DataProcessing do_Main_quick:^{
                complete( @{@"book" : marr});
            }];
        }];
    }];
}

- (void)_selectBookWithReadCountList_Books:(NSString *)bookIds complete:(void (^)(NSDictionary *))complete
{
    if (!complete || !bookIds) {
        return;
    }
    BOOL isChinese = [DataProcessing shareSingle].isChineseForLocalSystem;
    NSString* rCount = @"rCount";
    NSString* where = [NSString stringWithFormat:@"select bas.*,%@ from '%@' bas  left join '%@' babx  on bas.bookId=babx.bookId and bas.bookId in (%@) where bas.bookId in (%@)",rCount,[TABLE_BOOKS tableName],[TABLE_READING_COUNT tableName],bookIds,bookIds];
    [self readerDB:^(JRFMDatabase *db) {
        NSMutableArray* marr = [NSMutableArray new];
        NSArray* arr = [self getDictList_where:where db:db];
        for (NSDictionary* dict in arr) {
            TABLE_BOOKS* obj = [TABLE_BOOKS JRMJ_objectWithKeyValues:dict];
            if ([obj isKindOfClass:[TABLE_base class]]) {
                NSDictionary* replaceKeys = [[obj class] replacedKeyFromPropertyName];
                for (NSString* key in replaceKeys) {
                    id value = dict[key];
                    if (value && [obj hasProperty:key]) {
                        [obj setValue:value forKey:key];
                    }
                }
            }
            NSNumber* number = dict[rCount];
            nullToNil(number);
            obj.rCount = [number integerValue];
            obj.name_pinyin = isChinese ? obj.name_zh.pinyin : obj.name_en;
            if (obj) {
                [marr addObject:obj];
            }
        }
        [DataProcessing do_Main_quick:^{
            complete( @{@"book" : marr});
        }];
    }];
}


- (void)selectNotice:(void (^)(NSDictionary *))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"notice" : list});
        [self readerDB_deletListToTableClass:NSStringFromClass([TABLE_NOTICE class]) tbArr:list complete:nil];
    } fromTableClass:NSStringFromClass([TABLE_NOTICE class]) where:@""];
}

- (void)selectQuiz_Books:(NSString *)bookIds complete:(void (^)(NSDictionary *))complete
{
    //3.0 关闭了Quiz
    [DataProcessing do_Main_quick:^{
        if(complete)complete(@{@"quiz" : @[]});
    }];
    //
//    [self getList:^(NSArray *list) {
//        if(complete)complete(@{@"quiz" : list});
//    } fromTableClass:NSStringFromClass([TABLE_QUIZ class]) where:[NSString stringWithFormat:@" where bookId in (%@)",bookIds]];
}


- (void)selectSupportFiles:(void (^)(NSDictionary *))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"supportfiles" : list});
    } fromTableClass:NSStringFromClass([TABLE_SUPPORT_FILE class]) where:@""];
}

////
//- (void)selectMyBookListFor_uid:(NSInteger)uid complete:(void (^)(NSDictionary *))complete
//{
//    [self getList:^(NSArray *list) {
//        if(complete)complete(@{@"mybooklist" : list});
//    } fromTableClass:NSStringFromClass([TABLE_MYBOOKSHELF class]) where:[NSString stringWithFormat:@" where uid=%ld ORDER BY lastModifyDate desc ",(long)uid]];
//}
//


//
//- (void)cleanAllDeleteFor_uid:(NSInteger)uid complete:(void (^)(void))complete
//{
//    [self db_inQueue_executeUpdate:[NSString stringWithFormat:@"delete from %@ where uid=%d ",[TABLE_MYBOOKSHELF_Del tableName],uid] complete:complete];
//}


#pragma mark-
- (void)tbbooks_mutableArray:(NSMutableArray*)mArr orderBy_BookIds:(NSString*)bookids
{
    NSArray* arr = [bookids componentsSeparatedByString:@","];
    NSComparator compare = ^NSComparisonResult(TABLE_BOOKS* obj1, TABLE_BOOKS* obj2) {
        return [arr indexOfObject:@(obj1.bookId).description] > [arr indexOfObject:@(obj2.bookId).description];
    };
    //
    [mArr sortUsingComparator:compare];
}




#pragma mark-
#pragma mark- JoyReading_db
- (void)addNew_Reading_Recored:(TABLE_READ_RECORD *)tb_rrd
{
    [self sendNetLocalReadRecord_complete:^(JRFMDatabase *db) {
        if(tb_rrd)[self replaceListToTableClass:NSStringFromClass([TABLE_READ_RECORD class]) dictArr:@[[tb_rrd JRMJ_keyValues]] db:db];
    }];
}

- (void)update_TheReading_Recored:(TABLE_READ_RECORD *)tb_rrd
{
    [DataProcessing do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            if(tb_rrd)[self update_Only_ListToTableClass:NSStringFromClass([TABLE_READ_RECORD class]) dictArr:@[[tb_rrd JRMJ_keyValues]] db:db];
        }];
    }];
}
- (void)addReadingRecored:(NSString *)key dict:(NSDictionary *)dict
{
    if (dict && key) {
        NSError* error = nil;
        NSNumber* date = dict[@"date"];
        NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        if (error == nil && data) {
            NSString* value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [DataProcessing do_Async_quick:^{
                [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
                    TABLE_READ_RECORD_DICT* obj = [[TABLE_READ_RECORD_DICT alloc] init];
                    obj.key = key;
                    obj.value = value;
                    obj.createtime = date.longLongValue;
                    obj.remarks = [NSString stringWithFormat:@"%@:%@,%@",key,dict[@"type"],dict[@"mode"]];
                    NSDictionary* rcd = obj.replaceRecord;
                    NSString* sql = rcd[@"sql"];
                    NSDictionary* rdict = rcd[@"dict"];
                    if(![db executeUpdate:sql withParameterDictionary:rdict]){
                        NSLog(@"updateRecord_FromServer 数据失败 %@",[db lastError]);
                        NSLog(@"sql:>> %@",sql);
                    }
                }];
            }];
        }
    }
}


#pragma mark-
#pragma mark-Talk
- (void)selectTalk_Books:(NSString *)bookIds complete:(void (^)(NSDictionary *))complete
{
    [self readerDB_getList:^(NSArray *list) {
        if(complete)complete(@{@"talk" : list});
    } fromTableClass:NSStringFromClass([TABLE_TALK_LIST class]) where:[NSString stringWithFormat:@" where talkId in (%@)",bookIds]];
}

#pragma mark-
#pragma mark-TalkVedio
- (void)selectTalkVedioes:(NSString *)vedioIds complete:(void (^)(NSDictionary *))complete
{
    [self readerDB_getDictList:^(NSArray *list) {
        if(complete)complete(@{@"talkVedio" : list});
    } fromTableClass:NSStringFromClass([TABLE_TALK_VEDIO_LIST class]) where:[NSString stringWithFormat:@" where videoId in (%@)",vedioIds]];
}

#pragma mark-
#pragma mark-TalkInterviewVedio save
- (void)addNew_TalkUploadedInfo:(TABLE_TALK_SAVE_INFO *)tb_tksave
{
    [DataProcessing do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            if(tb_tksave)[self replaceListToTableClass:NSStringFromClass([TABLE_READ_RECORD class]) dictArr:@[[tb_tksave JRMJ_keyValues]] db:db];
            [DataProcessing do_Async_quick:^{
                [self sendNetTalkInfo_complete:^(JRFMDatabase *db) {}];
            }];
        }];
    }];
}


#pragma mark- 查询
- (NSArray* )getDictList_where:(NSString *)sql db:(JRFMDatabase *)db
{
    NSMutableArray* marr = [NSMutableArray array];
    NSString* select = sql;
#if __Debug_DBData_Check
    NSLog(@"select -->> %@",select);
#endif
    JRFMResultSet* rs_tb = [db executeQuery:select];
    if (rs_tb) {
        while ([rs_tb next]) {
            id obj = rs_tb.resultDictionary;
            if (obj) {
                [marr addObject:obj];
            }
#if __Debug_DBData_Check
            NSLog(@"Select Info %@-->>>%d,【%@】",tableClassName,marr.count,rs_tb.resultDictionary);
#endif
        }
    }
    return marr;
}

@end
